package com.sunny.setavatordemo.activity;

import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.sunny.setavatordemo.R;
import com.sunny.setavatordemo.constant.Config;
import com.sunny.setavatordemo.dialog.UploadConfirmDialog;
import com.sunny.setavatordemo.grid.adapter.GridAdapter;
import com.sunny.setavatordemo.grid.decoration.GridSpacingItemDecoration;
import com.sunny.setavatordemo.retrofit.RetrofitService;
import com.sunny.setavatordemo.retrofit.bean.UpLoadBean;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class PicturePickerActivity extends AppCompatActivity implements UploadConfirmDialog.OnDialogInteractionListener {

    private final static int spanCount = 3;
    private final static int spacing = 1;

    private List<String> pathList = new ArrayList<>();
    private GridAdapter.OnItemClickListener onItemClickListener
            = new GridAdapter.OnItemClickListener() {

        @Override
        public void onClick(int position) {


            UploadConfirmDialog dialog = UploadConfirmDialog.newInstance(pathList.get(position));

            dialog.addOnDialogInteractionListener(PicturePickerActivity.this);
            dialog.show(getSupportFragmentManager(), "confirm");
        }
    };

    private Uri imageUri;
    private ContentResolver contentResolver;
    private Cursor cursor;

    private RecyclerView recyclerView;
    private GridAdapter adapter;

    private Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {

            switch (msg.what) {
                case 1:
                    adapter.setData(pathList);
                    return;
            }
            super.handleMessage(msg);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_picture_picker);
        setTitle("选择头像");

        adapter = new GridAdapter();
        adapter.setOnItemClickListener(onItemClickListener);
        initView();

        imageUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
        contentResolver = getContentResolver();

        loadPic();
    }

    private void loadPic() {

        new Thread(new Runnable() {
            @Override
            public void run() {
                cursor = contentResolver.query(imageUri, null,
                        MediaStore.Images.Media.MIME_TYPE + "=? or "
                                + MediaStore.Images.Media.MIME_TYPE + "=?",
                        new String[]{"image/jpeg", "image/png"},
                        MediaStore.Images.Media.DATE_MODIFIED);
                while (cursor.moveToNext()) {
                    // 获取图片的路径
                    String path = cursor.getString(cursor
                            .getColumnIndex(MediaStore.Images.Media.DATA));
                    pathList.add(path);
                }

                handler.sendEmptyMessage(1);
            }
        }).start();

    }

    protected void initView() {

        recyclerView = findViewById(R.id.recyclerView);

        GridLayoutManager layoutManager =
                new GridLayoutManager(PicturePickerActivity.this, spanCount);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(adapter);
        recyclerView.addItemDecoration(new GridSpacingItemDecoration(spanCount, spacing, false));
    }


    @Override
    public void onDialogInteraction(int action, String path) {

        switch (action) {

            case 0:

                //上传头像
                uploadAvatar("lnn", path);
                break;
            case 1:

                finish();
                break;
        }
    }

    private void uploadAvatar(String username, final String avatar) {

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(Config.SERVER_BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        RetrofitService service = retrofit.create(RetrofitService.class);

        File file = new File(avatar);

        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);

//        RequestBody usernameBody = RequestBody.create(MediaType.parse("multipart/text"), username);
        RequestBody fileBody = RequestBody.create(MediaType.parse("image/png"), file);

        builder.addFormDataPart("username", username);
        builder.addFormDataPart("avatar", file.getName(), fileBody);

        MultipartBody multipartBody = builder.build();

        Call<UpLoadBean> call = service.uploadAvatar(multipartBody);

        call.enqueue(new Callback<UpLoadBean>() {

            @Override
            public void onResponse(Call<UpLoadBean> call, Response<UpLoadBean> response) {

                UpLoadBean upLoadBean = response.body();

                if (upLoadBean != null) {

                    if (upLoadBean.getRtn_code() == 0) {

                        Toast.makeText(PicturePickerActivity.this,
                                upLoadBean.getRtn_msg(),
                                Toast.LENGTH_SHORT).show();

                        Intent intent = new Intent();
                        intent.putExtra("path", avatar);
                        setResult(RESULT_OK, intent);
                        finish();

                    } else {

                        Toast.makeText(PicturePickerActivity.this,
                                upLoadBean.getRtn_msg(),
                                Toast.LENGTH_SHORT).show();
                    }
                }

            }

            @Override
            public void onFailure(Call<UpLoadBean> call, Throwable t) {

                Toast.makeText(PicturePickerActivity.this, t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }
}
